package br.com.tcf.login;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import br.com.tcf.ManegedBeans.ControlaAcessoMB;

public class FiltroNavegacao implements Filter{

	@Override
	public void destroy() {
		// TODO Auto-generated method stub

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		// TODO Auto-generated method stub
		System.out.println("Iniciando validação da pagina. FILTRO NAVEGACAO");

		HttpServletRequest httpRequest = (HttpServletRequest) request;
		String url = httpRequest.getRequestURI().toString();

		System.out.println("\n\n"+ "URL = "+ url);

		ControlaAcessoMB controlaAcessoMB = (ControlaAcessoMB) ((HttpServletRequest) request).getSession().getAttribute("controlaAcessoMB");

		System.out.println("Usuario logado: "+controlaAcessoMB.getUsuario().getNm_usuario());
		System.out.println("Permissao> "+controlaAcessoMB.verificaPermissao(url));

		if(controlaAcessoMB != null && controlaAcessoMB.getUsuario() != null){
			System.out.println(controlaAcessoMB.getUsuario().getNm_usuario().equals("MASTER"));
			if(controlaAcessoMB.getUsuario().getNm_usuario().equals("MASTER")){

				System.out.println("Acesso permitido");
				chain.doFilter(request, response);
			}
		}

		if(!controlaAcessoMB.getUsuario().getNm_usuario().equals("MASTER")){
			System.out.println("Entrou");
			if((controlaAcessoMB != null) && (controlaAcessoMB.getUsuario().getNm_usuario()!= null) &&(controlaAcessoMB.verificaPermissao(url)==true)){

				System.out.println("Acesso permitido");
				chain.doFilter(request, response);
			}else if ((controlaAcessoMB != null) && (controlaAcessoMB.getUsuario().getNm_usuario()!= null) &&(controlaAcessoMB.verificaPermissao(url)==false)){

				System.out.println("Negado!");

				HttpServletResponse hr = (HttpServletResponse)response;
				String context = httpRequest.getContextPath();
				if(controlaAcessoMB.getUsuario().getSn_administrador() == true){

					hr.sendRedirect(context+"/resourcePages/notAuthorizedAdm.xhtml");
				}else if(controlaAcessoMB.getUsuario().getSn_administrador() == false && controlaAcessoMB.getUsuario().getSn_empresa() == true){

					hr.sendRedirect(context+"/resourcePages/notAuthorizedEmpresa.xhtml");
				}
			}
		}
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub

	}
}
